﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CToolsWin.Files
{
    public partial class TXTFileMerge : Form
    {
        List<Dictionary<string, object>> listDicRule = new List<Dictionary<string, object>>();
        public TXTFileMerge()
        {
            InitializeComponent();
            cbbLineNumber.SelectedIndex = 0;
            cbbIsSaveFilName.SelectedIndex = 0;
            cbbIsClearFileContent.SelectedIndex = 0;
            cbbIsAllowEmptyFile.SelectedIndex = 0;
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.FileName = txtFileName.Text;
            fileDialog.ShowDialog();
            txtFileName.Text = fileDialog.FileName;
            if (string.IsNullOrEmpty(txtFileName.Text) == false)
            {
                bool isSuccess = false;
                string content = "";
                try
                {
                    content = Common.Files.FileHelper.FileToString(txtFileName.Text, Encoding.UTF8);
                    if (string.IsNullOrEmpty(content))
                    {
                        MessageBox.Show("配置文件内容不能为空");
                    }
                    else
                    {
                        listDicRule = Common.Serialize.JsonHelper.ToObject<List<Dictionary<string, object>>>(content);
                        isSuccess = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("文件内容格式有误");
                    Common.Msg.Log.GetLog.Error("文件内容格式有误", new { content }, ex);
                }
                finally
                {
                    if (isSuccess)
                    {
                        if (string.IsNullOrEmpty(txtFolderName.Text))
                            txtFolderName.Text = txtFileName.Text.Substring(0, txtFileName.Text.LastIndexOf('\\'));
                    }
                }
            }
        }

        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.SelectedPath = txtFolderName.Text;
            folderDialog.ShowDialog();
            txtFolderName.Text = folderDialog.SelectedPath;
        }

        private void btnNewSelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            if (string.IsNullOrEmpty(txtNewFolderName.Text))
                txtNewFolderName.Text = "D:\\";
            folderDialog.SelectedPath = txtNewFolderName.Text;
            folderDialog.ShowDialog();
            txtNewFolderName.Text = folderDialog.SelectedPath;
        }

        private void cbbIsSaveFilName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbIsSaveFilName.SelectedText == "是")
            {
                txtRuleFileNameKey.ReadOnly = true;
            }
            else
            {
                txtRuleFileNameKey.ReadOnly = false;
            }
        }

        private void btnStartMerge_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFileName.Text) || listDicRule == null || listDicRule.Count == 0)
                {
                    MessageBox.Show("请先选择正确的合并规则");
                    return;
                }
                if (string.IsNullOrEmpty(txtRuleFilePathKey.Text))
                {
                    MessageBox.Show("请输入正确的文件路径key");
                    return;
                }
                string folderName = "";
                if (string.IsNullOrEmpty(txtFolderName.Text) == false)
                {
                    folderName = txtFolderName.Text;
                }
                string fileNameSuffix = "";
                if (string.IsNullOrEmpty(txtFileNameSuffix.Text) == false)
                {
                    fileNameSuffix = "." + txtFileNameSuffix.Text.TrimStart('.');
                }
                string newFileName = "";
                if (string.IsNullOrEmpty(txtNewFileName.Text))
                {
                    newFileName = DateTime.Today.ToString("yyyyMMdd") + txtFileName.Text.Substring(txtFileName.Text.LastIndexOf('\\'));
                }
                else
                {
                    newFileName = txtNewFileName.Text;
                }
                if (newFileName.ToLower().Trim().EndsWith(".txt") == false)
                {
                    newFileName += ".txt";
                }
                string newFolderName = "";
                if (string.IsNullOrEmpty(txtNewFolderName.Text))
                {
                    newFolderName = txtNewFolderName.Text.Substring(0, txtNewFolderName.Text.LastIndexOf('\\'));
                }
                else
                {
                    newFolderName = txtNewFolderName.Text;
                }
                bool isSetRuleFileName = string.IsNullOrEmpty(txtRuleFileNameKey.Text) == false && cbbIsSaveFilName.SelectedText == "";
                //创建文件
                //循环规则
                //写
                using (var fs = System.IO.File.Create(System.IO.Path.Combine(newFolderName, newFileName)))
                {
                    string fileContent = "";
                    byte[] vs;
                    foreach (var item in listDicRule)
                    {
                        //读
                        fileContent = "";
                        if (isSetRuleFileName && item.ContainsKey(txtRuleFileNameKey.Text))
                        {
                            fileContent = item[txtRuleFileNameKey.Text].ToString() + fileContent + "\r\n";
                        }
                        if (item.ContainsKey(txtRuleFilePathKey.Text))
                        {
                            //判断文件是否存在
                            if (System.IO.File.Exists(System.IO.Path.Combine(folderName, item[txtRuleFilePathKey.Text].ToString() + fileNameSuffix)))
                            {
                                fileContent += "\t" + Common.Files.FileHelper.FileToString(System.IO.Path.Combine(folderName, item[txtRuleFilePathKey.Text].ToString() + fileNameSuffix), Encoding.UTF8).Trim();
                            }
                            else
                            {
                                if (cbbIsAllowEmptyFile.SelectedItem.ToString() != "是")
                                {
                                    MessageBox.Show("文件不存在");
                                    return;
                                }
                            }
                        }
                        else
                        {
                            continue;
                        }
                        if (cbbLineNumber.SelectedText != "0")
                        {
                            int qty = Convert.ToInt32(cbbLineNumber.SelectedItem);
                            string lineStr = "\r\n";
                            for (int i = 0; i < qty; i++)
                            {
                                lineStr += "\r\n";
                            }
                            fileContent += lineStr;
                        }
                        else
                            fileContent += "\r\n";
                        vs = System.Text.Encoding.UTF8.GetBytes(fileContent);
                        fs.Write(vs, 0, vs.Length);
                    }
                    MessageBox.Show("文件合并成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件合并错误");
                //TODO:日志
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            string msg = "1.合并规则文件内容由一个包含多个文件路径的json对象组成,如'[{\"path\":\"文件路径\",\"name\":\"文件名\"}]';";
            msg += "\r\n2.目录列没有值时默认合并规则中已包含文件完整路径;";
            msg += "\r\n3.没有输入文件名和保存目录时默认保存到合并规则所在文件夹,文件名为日期+规则文件文件名;";
            msg += "\r\n4.写入文件名时文件名占一行;";
            MessageBox.Show(msg);
        }

        private void btnShowConfig_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFileName.Text) || listDicRule == null || listDicRule.Count == 0)
            {
                MessageBox.Show("请先选择正确的合并规则");
                return;
            }

            var f = new ShowStr(Common.Serialize.JsonHelper.ToJson(listDicRule), CommonData.Data.StringType.Json);
            if (f.isSuccess)
            {
                f.ShowDialog();
            }
            else
            {
                MessageBox.Show("文件格式有误");
                //TODO:日志
            }
        }
    }
}
